package com.cloud.aop;


import com.cloud.beans.ResultBean;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

public class ControllerAspect {

    private static final Logger logger = Logger.getLogger(ControllerAspect.class);

    /**
     * Controller使用resultBean时会触发切面方法
     * @param pjp
     * @return
     */
    public Object handlerControllerMethod(ProceedingJoinPoint pjp){
        System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
        long startTime = System.currentTimeMillis();
        ResultBean<?> result;
        try {
            result = (ResultBean<?>) pjp.proceed();
            logger.error(pjp.getSignature() + "use time:" + (System.currentTimeMillis() - startTime));
        } catch (Throwable e) {
            result = handlerException(pjp, e);
        }
        System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx22");
        return result;
    }

    public void before(JoinPoint joinPoint){
        logger.info("前置方法");
        System.out.println("前置方法");
    }

    /**
     * 异常处理方法
     * @param pjp
     * @param e
     * @return
     */
    private ResultBean<?> handlerException(ProceedingJoinPoint pjp, Throwable e) {
        ResultBean<?> result = new ResultBean();
        result.setMsg(e.toString());
        result.setCode(ResultBean.FAIL);
        logger.error(e.toString());
        /*
        // 已知异常
        if (e instanceof CheckException) {
            result.setMsg(e.getLocalizedMessage());
            result.setCode(ResultBean.FAIL);
        } else if (e instanceof UnloginException) {
            result.setMsg("Unlogin");
            result.setCode(ResultBean.NO_LOGIN);
        } else {
            logger.error(pjp.getSignature() + " error ", e);
            //TODO 未知的异常，应该格外注意，可以发送邮件通知等
            result.setMsg(e.toString());
            result.setCode(ResultBean.FAIL);
        }
        */
        return result;
    }
}
